package com.suke.czx.modules.wx.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.suke.czx.common.utils.JsonResult;
import com.suke.czx.modules.wx.config.WxMpConfiguration;
import com.suke.czx.modules.wx.cons.Constant;
import com.suke.czx.modules.wx.vo.UserReadDays;
import com.suke.czx.modules.wxadmin.entity.DkReadPlanEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserAddressEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserReceiveEntity;
import com.suke.czx.modules.wxadmin.service.DkReadPlanService;
import com.suke.czx.modules.wxadmin.service.DkUserAddressService;
import com.suke.czx.modules.wxadmin.service.DkUserReceiveService;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@RestController
@RequestMapping("/wx/address/{appid}")
public class WxAddressController extends BaseController {
	
	private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private DkUserAddressService dkUserAddressService;

	@Autowired
	private DkUserReceiveService dkUserReceiveService;

	@Autowired
	private DkReadPlanService dkReadPlanService;

	@RequestMapping("/info/{openid}")
	public String info(@PathVariable("openid") String openid) {
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}

		DkUserAddressEntity dkUserAddress = dkUserAddressService.queryObject(openid);
		if (null == dkUserAddress) {
			return new JsonResult(201, "没有登记过地址信息，跳转登记界面").toJson();
		}
		// 获取打卡计划构建四次领书相关信息
		JSONObject obj = new JSONObject();

		List<DkReadPlanEntity> list = dkReadPlanService.queryUserReadPlanById(wxMpUser.getOpenId());
		if (null == list || list.size() == 0) {
			obj.put("first", "未完成");
			obj.put("second", "未完成");
			obj.put("third", "未完成");
			obj.put("fourth", "未完成");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("times", obj);
			map.put("address", dkUserAddress);
			return new JsonResult(200, "没有书可以领取！", map).toJson();
		}
		UserReadDays readDays = dkReadPlanService.getUserReadDays(openid);
		if (wxMpUser.getOpenId().equals("ovy7t0wVOXy0kO6G_FH0c6OZyOyc")
				|| wxMpUser.getOpenId().equals("ovy7t08FmYRciJ7iVKxrKk5Nvi1k")) {
			readDays.setTmp_continuousReadDays(100);
		}
		int n = readDays.getTmp_continuousReadDays();
		if (n >= 45 & n < 90) {
			obj.put("first", "可领取");
			obj.put("second", "未完成");
			obj.put("third", "未完成");
			obj.put("fourth", "未完成");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("times", obj);
			map.put("address", dkUserAddress);
			return new JsonResult(200, "ok", map).toJson();
		}
		if (n >= 90 & n < 135) {
			obj.put("first", "可领取");
			obj.put("second", "可领取");
			obj.put("third", "未完成");
			obj.put("fourth", "未完成");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("times", obj);
			map.put("address", dkUserAddress);
			return new JsonResult(200, "ok", map).toJson();
		}
		if (n >= 135 & n < 180) {
			obj.put("first", "可领取");
			obj.put("second", "可领取");
			obj.put("third", "可领取");
			obj.put("fourth", "未完成");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("times", obj);
			map.put("address", dkUserAddress);
			return new JsonResult(200, "ok", map).toJson();
		}
		if (n >= 180) {
			obj.put("first", "可领取");
			obj.put("second", "可领取");
			obj.put("third", "可领取");
			obj.put("fourth", "可领取");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("times", obj);
			map.put("address", dkUserAddress);
			return new JsonResult(200, "ok", map).toJson();
		}

		obj.put("first", "未完成");
		obj.put("second", "未完成");
		obj.put("third", "未完成");
		obj.put("fourth", "未完成");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("times", obj);
		map.put("address", dkUserAddress);
		return new JsonResult(200, "没有书可以领取！", map).toJson();
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public String save(@RequestBody DkUserAddressEntity dkUserAddress) {

		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		dkUserAddress.setOpenid(wxMpUser.getOpenId());
		dkUserAddress.setHeadimg(wxMpUser.getHeadImgUrl());
		dkUserAddress.setNikename(wxMpUser.getNickname());
		dkUserAddress.setCreatetime(new Date());

		dkUserAddressService.save(dkUserAddress);
		return new JsonResult(200, "ok", dkUserAddress).toJson();
	}
	
	
	/**
	 * 更新
	 */
	@RequestMapping("/update")
	public String update(@RequestBody DkUserAddressEntity dkUserAddress) {

		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		dkUserAddress.setOpenid(wxMpUser.getOpenId());
		dkUserAddress.setHeadimg(wxMpUser.getHeadImgUrl());
		dkUserAddress.setNikename(wxMpUser.getNickname());
		dkUserAddress.setCreatetime(new Date());
		dkUserAddressService.update(dkUserAddress);
		return new JsonResult(200, "ok", dkUserAddress).toJson();
	}

	@RequestMapping("/receive/index/{times}")
	public String receive_index(@PathVariable("times") String times) {

		if (null == times) {
			return new JsonResult(202, "非法请求，请从正常入口进来！").toJson();
		}

		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		DkUserAddressEntity dkUserAddress = dkUserAddressService.queryObject(wxMpUser.getOpenId());
		Map<String, Object> dateMap = new HashMap<String, Object>();
		dateMap.put("address", dkUserAddress);
		
		Map<String,String> parms = new HashMap<String,String>();
		parms.put("openid", wxMpUser.getOpenId());
		parms.put("times", times);
		List<DkUserReceiveEntity> list1 = dkUserReceiveService.queryByOpenidAndTimes(parms);
		if(null!=list1&&list1.size()>0){
			dateMap.put("receive", list1.get(0));
			int flag = list1.get(0).getBookId();
			if(flag==1){
				dateMap.put("flag", "审核中");
			}else if(flag==2){
				dateMap.put("flag", "审核通过,待发货！");
			}else if(flag==3){
				dateMap.put("flag", "审核不通过，请重新上传！");
			}else if(flag==4){
				dateMap.put("flag", "已发货");
			}else if(flag==5){
				dateMap.put("flag", "未通过审核，不予赠书！");
			}else{
				dateMap.put("flag", "状态不明朗，请联系客服！");
			}
			return new JsonResult(88, "已经登记过相关信息，显示即可！", dateMap).toJson();
		}
		
		UserReadDays readDays = dkReadPlanService.getUserReadDays(wxMpUser.getOpenId());
		int i1 = 10;
		int i2 = 21;
		int i3 = 33;
		

		if (wxMpUser.getOpenId().equals("ovy7t0wVOXy0kO6G_FH0c6OZyOyc")
				|| wxMpUser.getOpenId().equals("ovy7t08FmYRciJ7iVKxrKk5Nvi1k")) {
			readDays.setTmp_continuousReadDays(100);
			dateMap.put("date1", "2019-02-24");
			dateMap.put("date2", "2019-02-25");
			dateMap.put("date3", "2019-02-26");
			return new JsonResult(200, "ok", dateMap).toJson();
		}
		// 1、如果是第一次领书判断领书相关罗逻辑生成三个日期
		if (times.equals("first") && readDays.getTmp_continuousReadDays() >= 45) {
			List<DkReadPlanEntity> list = dkReadPlanService.queryUserReadPlanById(wxMpUser.getOpenId());
			dateMap.put("date1", list.get(i1).getReadDate());
			dateMap.put("date2", list.get(i2).getReadDate());
			dateMap.put("date3", list.get(i3).getReadDate());
		} else if (times.equals("second") && readDays.getTmp_continuousReadDays() >= 90) {
			List<DkReadPlanEntity> list = dkReadPlanService.queryUserReadPlanById(wxMpUser.getOpenId());
			dateMap.put("date1", list.get(i1 + 45).getReadDate());
			dateMap.put("date2", list.get(i2 + 45).getReadDate());
			dateMap.put("date3", list.get(i3 + 45).getReadDate());
		} else if (times.equals("third") && readDays.getTmp_continuousReadDays() >= 135) {
			List<DkReadPlanEntity> list = dkReadPlanService.queryUserReadPlanById(wxMpUser.getOpenId());
			dateMap.put("date1", list.get(i1 + 90).getReadDate());
			dateMap.put("date2", list.get(i2 + 90).getReadDate());
			dateMap.put("date3", list.get(i3 + 90).getReadDate());
		} else if (times.equals("fourth") && readDays.getTmp_continuousReadDays() >= 180) {
			List<DkReadPlanEntity> list = dkReadPlanService.queryUserReadPlanById(wxMpUser.getOpenId());
			dateMap.put("date1", list.get(i1 + 135).getReadDate());
			dateMap.put("date2", list.get(i2 + 135).getReadDate());
			dateMap.put("date3", list.get(i3 + 135).getReadDate());
		} else {
			return new JsonResult(205, "目前你还不符合领书要求", dateMap).toJson();
		}
		return new JsonResult(200, "ok", dateMap).toJson();
	}

	@PostMapping(value="/receive/save/{times}",produces = "application/json; charset=UTF-8")
	public String receive_save(@PathVariable("times") String times, @RequestBody String requestBody) {
		JSONObject obj = JSONObject.parseObject(requestBody);
		String date1 = obj.getString("date1");
		String img1 = obj.getString("img1");
		String date2 = obj.getString("date2");
		String img2 = obj.getString("img2");
		String date3 = obj.getString("date3");
		String img3 = obj.getString("img3");
		String bookname = obj.getString("bookname");
		String startdate = obj.getString("startdate");
		logger.info("==========>times:" + times);
		logger.info("==========>date1:" + date1);
		logger.info("==========>img1:" + img1);
		logger.info("==========>date2:" + date2);
		logger.info("==========>img2:" + img2);
		logger.info("==========>date3:" + date3);
		logger.info("==========>img3:" + img3);
		logger.info("==========>bookname:" + bookname);
		logger.info("==========>startdate:" + startdate);
		
		
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		
		Map<String,String> parms = new HashMap<String,String>();
		parms.put("openid", wxMpUser.getOpenId());
		parms.put("times", times);
		List<DkUserReceiveEntity> list = dkUserReceiveService.queryByOpenidAndTimes(parms);
		if(list!=null && list.size()>0){
			return new JsonResult(200, "本次领书您已经登记过了！").toJson();
		}
		
		UserReadDays readDays = dkReadPlanService.getUserReadDays(wxMpUser.getOpenId());
//ovy7t0wPiOUGfojsfgtoIPnH4oWc
		if (wxMpUser.getOpenId().equals("ovy7t0wVOXy0kO6G_FH0c6OZyOyc")
				|| wxMpUser.getOpenId().equals("ovy7t08FmYRciJ7iVKxrKk5Nvi1k")|| wxMpUser.getOpenId().equals("ovy7t0wPiOUGfojsfgtoIPnH4oWc")) {
			readDays.setTmp_continuousReadDays(100);
		}
		if (times.equals("first")) {
			if (readDays.getTmp_continuousReadDays() < 45) {
				return new JsonResult(209, "不符合申请领书要求").toJson();
			}
		} else if (times.equals("second")) {
			if (readDays.getTmp_continuousReadDays() < 90) {
				return new JsonResult(209, "不符合申请领书要求").toJson();
			}

		} else if (times.equals("third")) {
			if (readDays.getTmp_continuousReadDays() < 135) {
				return new JsonResult(209, "不符合申请领书要求").toJson();
			}

		} else if (times.equals("fourth")) {
			if (readDays.getContinuousReadDays() < 180) {
				return new JsonResult(209, "不符合申请领书要求").toJson();
			}

		} else {
			return new JsonResult(209, "不符合申请领书要求").toJson();
		}
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wx110e4b18284caf04");
		// 获得一个在系统临时目录的文件
		String basePath = "/www/wwwroot/dk2019.hbanbao.com/receiveimg/";
		
		try {
			File file1 = wxMpService.getMaterialService().mediaDownload(img1);
			copyFile(file1, basePath+wxMpUser.getOpenId()+"_"+times+"_"+date1+".jpg");
			File file2 = wxMpService.getMaterialService().mediaDownload(img2);
			copyFile(file2, basePath+wxMpUser.getOpenId()+"_"+times+"_"+date2+".jpg");
			File file3 = wxMpService.getMaterialService().mediaDownload(img3);
			copyFile(file3, basePath+wxMpUser.getOpenId()+"_"+times+"_"+date3+".jpg");
			DkUserReceiveEntity dur = new DkUserReceiveEntity();
			dur.setBookId(1);
			dur.setBookName(bookname);
			dur.setCreatetime(new Date());
			dur.setDate1(date1);
			dur.setDate2(date2);
			dur.setDate3(date3);
			dur.setImg1("http://dk2019.hbanbao.com/receiveimg/"+wxMpUser.getOpenId()+"_"+times+"_"+date1+".jpg");
			dur.setImg2("http://dk2019.hbanbao.com/receiveimg/"+wxMpUser.getOpenId()+"_"+times+"_"+date2+".jpg");
			dur.setImg3("http://dk2019.hbanbao.com/receiveimg/"+wxMpUser.getOpenId()+"_"+times+"_"+date3+".jpg");
			dur.setOpenid(wxMpUser.getOpenId());
			dur.setStartTime(startdate);
			dur.setTimes(times);
			dkUserReceiveService.save(dur);
			
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(209, "图片上传失败").toJson();
		}
		return new JsonResult(200, "领书登记成功，我们会尽快发货！").toJson();
	}
	
	
	@PostMapping(value="/receive/update/{times}",produces = "application/json; charset=UTF-8")
	public String receive_update(@PathVariable("times") String times, @RequestBody String requestBody) {
		JSONObject obj = JSONObject.parseObject(requestBody);
		String date1 = obj.getString("date1");
		String img1 = obj.getString("img1");
		String date2 = obj.getString("date2");
		String img2 = obj.getString("img2");
		String date3 = obj.getString("date3");
		String img3 = obj.getString("img3");
		String bookname = obj.getString("bookname");
		String startdate = obj.getString("startdate");
		logger.info("==========>times:" + times);
		logger.info("==========>date1:" + date1);
		logger.info("==========>img1:" + img1);
		logger.info("==========>date2:" + date2);
		logger.info("==========>img2:" + img2);
		logger.info("==========>date3:" + date3);
		logger.info("==========>img3:" + img3);
		logger.info("==========>bookname:" + bookname);
		logger.info("==========>startdate:" + startdate);
		
		
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if (null == wxMpUser) {
			return new JsonResult(24, "用户未登录，请先登录！").toJson();
		}
		
		Map<String,String> parms = new HashMap<String,String>();
		parms.put("openid", wxMpUser.getOpenId());
		parms.put("times", times);
		List<DkUserReceiveEntity> list = dkUserReceiveService.queryByOpenidAndTimes(parms);
		if(list!=null && list.size()>0){
			WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wx110e4b18284caf04");
			// 获得一个在系统临时目录的文件
			String basePath = "/www/wwwroot/dk2019.hbanbao.com/receiveimg/";
			
			try {
				File file1 = wxMpService.getMaterialService().mediaDownload(img1);
				copyFile(file1, basePath+wxMpUser.getOpenId()+"_"+times+"_"+date1+".jpg");
				File file2 = wxMpService.getMaterialService().mediaDownload(img2);
				copyFile(file2, basePath+wxMpUser.getOpenId()+"_"+times+"_"+date2+".jpg");
				File file3 = wxMpService.getMaterialService().mediaDownload(img3);
				copyFile(file3, basePath+wxMpUser.getOpenId()+"_"+times+"_"+date3+".jpg");
				DkUserReceiveEntity dur = list.get(0);
				dur.setBookId(1);
				dur.setBookName(bookname);
				dur.setCreatetime(new Date());
				dur.setDate1(date1);
				dur.setDate2(date2);
				dur.setDate3(date3);
				dur.setImg1("http://dk2019.hbanbao.com/receiveimg/"+wxMpUser.getOpenId()+"_"+times+"_"+date1+".jpg");
				dur.setImg2("http://dk2019.hbanbao.com/receiveimg/"+wxMpUser.getOpenId()+"_"+times+"_"+date2+".jpg");
				dur.setImg3("http://dk2019.hbanbao.com/receiveimg/"+wxMpUser.getOpenId()+"_"+times+"_"+date3+".jpg");
				dur.setStartTime(startdate);
				dkUserReceiveService.update(dur);
				
			} catch (Exception e) {
				e.printStackTrace();
				return new JsonResult(209, "图片上传失败").toJson();
			}
			
		}else{
			return new JsonResult(200, "本次领书您已经登记过了！").toJson();
		}
		return new JsonResult(200, "领书登记成功，我们会尽快发货！").toJson();
	}

	public void copyFile(File oldfile, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldfile); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
